"""
Wang Shigui
"""
import cv2
import numpy as np

path = '../../../../large_data/video/cam/save_blue_video.avi'
red = cv2.VideoCapture(path)
out = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('out.avi',out,20.0,(640,480))

blue1 = np.float32([100, 50, 50])
blue2 = np.float32([130, 255, 255])
kernel = np.ones((7,7),np.uint8)

while (1):
    reds, flmas = red.read()
    flma = flmas[298:474,149:400]
    if flma is None:
        break
    hsv = cv2.cvtColor(flma, cv2.COLOR_BGR2HSV)
    mor = cv2.inRange(hsv, blue1, blue2)
    mor = cv2.medianBlur(mor,5)
    #
    ret,franms = cv2.threshold(mor,25,255,cv2.THRESH_BINARY)
    franms = cv2.morphologyEx(franms,cv2.MORPH_OPEN,kernel)
    dst = cv2.bitwise_and(flma,flma,mask=franms)
    contours,hierarchy = cv2.findContours(franms,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

    for cnt in contours:
        (x,y,w,h) = cv2.boundingRect(cnt)
        cv2.rectangle(flma,(x,y),(x+w,y+h),(0,255,255),2)
        cv2.putText(flma,'blue',(x,y-10),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,0),2)

    cv2.imshow('img',flma)
    cv2.imshow('v',dst)
    cv2.imshow('mor', franms)
    if cv2.waitKey(100) & 0xff == ord('q'):
        break

red.release()
cv2.destroyAllWindows()